import React, { useState } from 'react';
import NumberField from '../../../../components/common/NumberField';
import StatefulCalculationCard from '../../../../components/common/StatefulCalculationCard';
import ExportData from '../../../../components/common/ExportCalculateData';
import type { ResultItem } from '../../../../../shared/types';

// 定义表单数据类型
export interface FormValues {
  gamma_f: number;
  h_f: number;
  h1: number;
  lambda_1: number;
}

// 计算结果类型定义
export interface FormResult {
  e1: number;
  e1_prime: number;
}

// 计算初始值配置
const initialValues: FormValues = {
  gamma_f: 20.0,
  h_f: 10.5,
  h1: 10.0,
  lambda_1: 0.5,
};

// 计算卡片组件配置
const CalculationConfig = {
  key: 'LateralSoilPressureCalculation',
  label: '侧向土压力计算',
  formKey: 'lateral-soil-pressure-calculation',
  initialValues: initialValues,
  calculationType: 'lateral-soil-pressure',
  resultFormatter: (data: FormResult) => [
    { key: 'e1', name: 'e1（左侧拱部侧向土压力）', value: typeof data.e1 === 'number' ? Number(data.e1.toFixed(2)) : data.e1, unit: 'kN/m²' },
    { key: "e1'", name: "e1'（左侧底部侧向土压力）", value: typeof data.e1_prime === 'number' ? Number(data.e1_prime.toFixed(2)) : data.e1_prime, unit: 'kN/m²' },
  ],
  renderFormFields: () => (
    <>
      <NumberField name="gamma_f" label="土体重度γf (kN/m³)" required min={0} step={0.1} tooltip="土体的重度" />
      <NumberField name="h_f" label="上层土厚度hf (m)" required min={0} step={0.1} tooltip="隧道拱部溶洞充填物到拱顶的厚度" />
      <NumberField name="h1" label="底部深度h1 (m)" required min={0} step={0.1} tooltip="溶洞充填物左侧底部右侧底部的深度" />
      <NumberField name="lambda_1" label="侧压力系数λ1" required min={0} step={0.1} tooltip="溶洞充填物左侧侧压力系数，右侧侧压力系数" />
    </>
  ),
  optimizedFormula: "e_1 = \\gamma_f h_f \\lambda_1 \\quad e_1' = \\gamma_f (h_f + h_1) \\lambda_1",
};

// 计算卡片组件实现
const LateralSoilPressureCard: React.FC = () => {
  const [lastResults, setLastResults] = useState<ResultItem[] | null>(null);
  
  return (
    <StatefulCalculationCard
      title={CalculationConfig.label}
      formKey={CalculationConfig.formKey}
      initialValues={CalculationConfig.initialValues}
      renderFormFields={CalculationConfig.renderFormFields}
      calculationType={CalculationConfig.calculationType}
      resultFormatter={(data) => {
        const results = CalculationConfig.resultFormatter(data);
        setLastResults(results);
        return results;
      }}
      columnCount={1} // 使用1列布局
      tableHeight={300} // 设置表格高度为300px
      formula={CalculationConfig.optimizedFormula}
      exportComponent={(form) => (
        <ExportData
          siteName={CalculationConfig.label}
          inputs={form.getFieldsValue()}
          results={lastResults ? Object.fromEntries(lastResults.map(r => [r.key, r.value])) : {}}
          calculationType={CalculationConfig.calculationType}
        />
      )}
    />
  );
};

export default LateralSoilPressureCard;